<div class="page-wrapper">
    <div class="header">
        <div class="left">
            <div id="waiter-name" class="name"><i class="icon-me"></i><span class="text">未登录</span></div>
        </div>
        <div class="right">
            <!--<i id="waiter-reload" class="icon-refresh"></i>-->
            <!--<span id="waiter-logout" class="logout">退出</span>-->
            <a href="#action=waiter_setting"><span id="waiter-setting">设置</span></a>
        </div>
    </div>
    <div class="table-wrapper">
        <div id="nav-tabs" class="tab">
            <div class="tab-item selected">台桌</div>
            <div class="tab-item">订单</div>
        </div>
        <div id="nav-waiter-content" class="content">
            <div class="wrapper">
                <div class="table-list">
                    <div id="repeat-table-item" class="table-item" style="display:none">
                        <div class="item">
                            <!--<i class="icon-addfood append"></i>-->
                            <div class="t_name"></div>
                            <div class="t_state">空闲</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wrapper home-orders-body" style="display: none;">
                <div class="table-order-list">
                    <div id="unconfirmed-orders" class="order-group" style="display: none;">
                        <div class="title"><div class="text">待处理</div><hr></div>
                    </div>

                    <div id="confirmed-orders" class="order-group" style="display: none;">
                        <div class="title"><div class="text">进行中</div><hr></div>
                    </div>

                    <div class="no-message" style="display: none">当前没有要处理的订单(^=^)</div>

                </div>

                <div id="repeat-waiter-home-order" class="order-g-item" style="display: none;">
                    <div class="order-des">
                        <div class="table-name">A12</div>
                        <div class="message">
                            <div class="line waiter-home-order-number">订单编号：<span class="text">22</span></div>
                            <div class="line waiter-home-order-time">下单时间：<span class="text">2016-09-18 10:14</span></div>
                            <div class="line waiter-home-order-from">订单来源：<span class="text">微信(vision_小词)</span></div>
                        </div>
                    </div>
                    <div class="order-op">
                        <div class="price waiter-home-order-price">￥328</div>
                        <div class="btns">
                            <button class="btn white waiter-home-order-append">打印</button>
                            <button class="btn waiter-home-order-pay">结账</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        (function(){
            'use strict';
            console.log('tables.html');

            $('#waiter-name').find('.text').text($.cookie('cookie_username'));

            var TableState={
                IDLE:0,
                USING:1
            }

            $('#waiter-reload').on('click',function(){
                location.reload();
            });

            $('#waiter-logout').on('click',function(){
                $.ajax({
                    url:'/api/waiter/logout',
                    dataType:'json',
                    type:'post',
                    contentType:'application/json;charset=utf-8'
                }).done(function(data){
                   location.reload();
                }).fail(function(data){
                    location.reload();
                });
            });


            //tab 切换事件
            $('#nav-tabs .tab-item').click(function(){
               if($(this).hasClass('.selected')) return;

                var index = $(this).index();

                $(this).siblings('.selected').removeClass('selected');
                $(this).addClass('selected');

                $('#nav-waiter-content .wrapper').hide();
                var item = $('#nav-waiter-content .wrapper')[index]; //显示选择的页面
                $(item).show();
                if($(this).text() == "台桌"){


                    resizeTableItem();
                }
            });

            spa.addResumeCallback(function(){
                console.log('tables.html addResumeCallback')
                //修改台桌状态
                $.getJSON('/api/table/storeid/' + window.storeId,{},function(data){
                    var $tables = $('#repeat-table-item').siblings('.table-item');
                    $.each(data,function(index,item){
                        var table = $tables[index];
                        setTableState($(table),item);
                    });
                });
                //修改订单状态
//                getStoreOrders();
            });

            function showStoreTables() {
                var success = function(data){
                    console.log(data);
                    if($('.table-item').length <= 1){ //没有台桌
                        $.each(data,function(index,item){
                            addTable(item);
                        });
                    }else{ //修改台桌状态
                        $.each(data,function(index,item){
                            var $table = $('.table-item[t-id='+item.id+']');
                            setTableState($table,item);
                        });
                    }
                };
                var error = function(){
                    console.log('获取台桌列表错误');
                };
//                api.getTableNotifyList(window.storeId,success,error);
                api.startTableStateTick(window.storeId,success,error); //定时更新列表
            }

            function addTable(item){
                var $newItem = cloneItem();
                $newItem.attr('t-id',item.id);
                $newItem.attr('t-name',item.name);
                $newItem.find('.t_name').text(item.name);
                $newItem.attr('t-seating',item.seating);
                $newItem.attr('t-state',item.state);
                setTableState($newItem,item);
                $newItem.css({'visibility':'hidden'});
                $repeatTableItem.before($newItem);
                var $innerItem = $newItem.find('.item');
                var width = $innerItem.width();
                $innerItem.height(width);
                $innerItem.css({'line-height':width + 'px'});
                $innerItem.css({'visibility':'visible'});
                $newItem.on("click", tableClicked);
            }
            
            var appendStr = "";

            function tableClicked() {
                var state = $(this).attr('t-state');
                var tableId = $(this).attr('t-id');
                var tableName = $(this).attr('t-name');

                appendStr = "&tableId=" + tableId + "&tableName=" + tableName;
                window.tableId = tableId;
                if (cart.tableId() != tableId) {
                    window.initCart();
                    cart.tableId(tableId);
                }
                var tableSeating = $(this).attr('t-seating');
                cart.people(parseInt(tableSeating));
                location.href="#action=waiter_menus"+appendStr;

            }

            $(window).resize(function(){
                resizeTableItem();
            });

            function resizeTableItem(){
                console.log('resize');
                var $tableItem = $('.table-list .item');
                var width = $tableItem.width();
                $tableItem.height(width);
                $tableItem.css({'line-height':width + 'px'});
            }

            function  setTableState($table,item) {
                var $state = $table.find('.t_state');
                if(item.state == TableState.USING){
                    $table.addClass('not-idle');
                    $table.attr('t-state',item.state);
                    $state.text('就餐中...');
                }else{
                    $table.removeClass('not-idle');
                    $state.text(item.seating + "人");
                }
            }

            $('.cancel').on('click', function () {
                $('#confirm-dialog').hide();
            });

            $('.confirm').click(function(){
                $('#confirm-dialog').hide();
                cart.people($('#dlg-seating').val());
                cart.save();
                location.href="#action=waiter_menus"+appendStr;
            });

            var $repeatTableItem = undefined;
            function cloneItem(){
                if(!$repeatTableItem){
                    $repeatTableItem = $('#repeat-table-item');
                }
                var $item = $repeatTableItem.clone();
                $item.show();
                $item.attr('id',Date.now());
                return $item;
            }

            var $repeatWaiterHomeOrderItem = undefined;
            function cloneWaiterHomeOrderItem() {
                if(!$repeatWaiterHomeOrderItem){
                    $repeatWaiterHomeOrderItem = $('#repeat-waiter-home-order');
                }
                var $item = $repeatWaiterHomeOrderItem
                        .clone()
                        .show()
                        .attr('id','');
                return $item;
            }

            var timerId;
            var lastGetterTime;
            //订单
            function getStoreOrders() {//获取待确认订单...
                $.getJSON('/waiterOrder/api/getStoreConfirmOrder/'+storeId+'/0','',function(data){
                    console.log(data);
                    lastGetterTime = data.lastUpdateDate;
                    if(data && data.total){
                        hideNoOrders();
                        console.log('getStoreConfirmOrder');
                        showUnconfirmedOrderList(data.result);
                    }else{
                        console.log('no data');
                        showNoOrders();
                    }

                }).fail(function(){
                    showNoOrders();
                });

                $.getJSON('/waiterOrder/api/getStoreNopayOrder/'+storeId+'/0','',function (data) {
                    console.log(data);

                    if(data && data.total){
                        hideNoOrders();
                        console.log('getStoreNopayOrder');
                        showConfirmedOrderList(data.result);
                    }else{
                        showNoOrders();
                    }
                }).fail(function(){
                    showNoOrders();
                });

                cycleGetter();
            }

            function stopCycleGetter() {
                if(timerId){
                    clearInterval(timerId);
                }
            }
            window.getDiff = function(){
                var url = '/waiterOrder/api/getOrderNotifyList/' + window.storeId;
                if(!lastGetterTime) return;

                $.post(url,{lastUpdateDate:lastGetterTime},function(data){

                    if(data && data.lastUpdateDate){
                        lastGetterTime = data.lastUpdateDate;
                    }

                    if(data && data.confirmOrderList && data.confirmOrderList.length){ //待确认列表数据发生变化
                        hideNoOrders();
                        var list = data.confirmOrderList;
                        $.each(list,function(index,item){
                            if(item.state == OrderState.unconfirmed){
                                showUnconfirmedOrderItem(item);
                            }else{ //从待确认列表中删除对应项
                                console.log($('#unconfirmed-orders .order-g-item[order-id='+item.orderId+']'));
                                $('#unconfirmed-orders .order-g-item[order-id='+item.orderId+']').remove();
                                ifHideUnconfirmedList();
                            }
                        });
                    }

                    if(data && data.nopayOrderList && data.nopayOrderList.length){
                        hideNoOrders();
                        var list = data.nopayOrderList;
                        $.each(list,function (index,item) {
                            var $item = $('#confirmed-orders .order-g-item[order-id='+item.orderId+']');
                            if(item.state == OrderState.confirmed){ //在 进行中 列表添加或者修改Item

                                if($item.length > 0){ //update
                                    setOrderItemCommonStatus($item,item);
                                }else{  //新增
                                    //showConfirmedOrderList()
                                    showConfirmedItem(item,true);
                                }

                            }else{ //删除
                                $item.remove();
                                ifHideConfirmedList();
                            }
                        });
                    }

                });
            };
            /**
            * 每隔10s从服务器获取一次数据
            */
            function cycleGetter() {
                timerId = setInterval(getDiff,10 * 1000);
            }

            function resetConfirmedOrdersList() {
                $('#confirmed-orders').hide().children('.order-g-item').remove();
            }

            function resetUnconfirmedOrdersList(){
                $('#unconfirmed-orders').hide().children('.order-g-item').remove();
            }

            function setConfirmedOrderItem($item){
                if($('#confirmed-orders').is(':hidden')){
                    console.log('显示 confirmed-orders');
                    $('#confirmed-orders').show();
                    hideNoOrders();
                }

                if(window.hasPrinter){
                    $item.find('.waiter-home-order-append').text('打印').on('click',function(){
                        var orderId = $(this).parents('.order-g-item').attr('order-id');
                        printer.isConnected(function (data) {
                            if(data.isConnected){
                                printOrder(orderId);
                            }
                        })
                        return false;
                    }).show();
                }else{
                    $item.find('.waiter-home-order-append').hide();
                }


                $item.find('.waiter-home-order-pay').on('click',function(){

                    var tId = $(this).parents('.order-g-item').attr('table-id');
                    //收款
                    location.href="#action=waiter_qr&from=首页&tableId="+tId;

                    return false;
                }).text('结账');
            }

            /**
             *打印订单
             */
            function printOrder(orderId) {
                api.getOrder(orderId,function (data) {
                    var order = data.order;
                    var originalPrice = order.originalPrice;
                    var price = order.price;
                    order.coupon = (originalPrice - price).toFixed(1)
                    printer.printOrder(data);
                },function(){
                    common.toast('获取订单失败，请重试...');
                });
            }

            function setUnconfirmedOrderItem($item){

                $item.find('.waiter-home-order-append')
                        .show()
                        .on('click',function(){
                            var $parent = $(this).parents('.order-g-item');
                            var subOrderId = $parent.attr('order-id');
                            refuse(subOrderId,$parent);
                            return false;
                        }).text('拒绝');
                $item.find('.waiter-home-order-pay')
                        .show()
                        .on('click',function(){

                            var $parent = $(this).parents('.order-g-item');
                            var subOrderId = $parent.attr('order-id');

                            accept(subOrderId,$parent);

                            return false;
                        }).text('确认');
            }
            function setOrderItemCommonStatus($item,orderItem){

                var orderId = orderItem.orderId;
                var time  = orderItem.createDate;
                var price = common.fixOne(orderItem.price);
                var tId = orderItem.tableId;
                var tableName = orderItem.tableName
                $item.attr('order-id',orderId);
                $item.attr('table-id',tId);
                $item.find('.table-name').text(tableName);
                $item.find('.waiter-home-order-number .text').text(orderId);
                $item.find('.waiter-home-order-time .text').text(time);
                $item.find('.waiter-home-order-price').text('￥'+ price);
            }


            /**
             * 取消订单
             */
            function refuse(id,$item){
                console.log('refuse ' + id);

                if(confirm("您确定拒绝此订单吗？")){
                    $.getJSON('/waiterOrder/api/refuseOrder/'+id,'',function (data) {
                        if(data.status === 'success'){
                            common.toast('订单已拒绝');
//                            $item.fadeOut(function(){
//                                $item.remove();
//                                if($('#nconfirmed-orders .order-g-item').length == 0){
//                                    $('#unconfirmed-orders').fadeOut();
//                                }
//                            });
                            if(window.getDiff){
                                window.getDiff();
                            }
                        }else{
                            common.toast('拒绝订单失败');
                        }
                    });
                }
            }
            /**
             * 接受订单
             */
            function accept(id,$item){
                console.log('accept ' + id);
                $.getJSON('/waiterOrder/api/acceptOrder/'+id,'',function(data){
                    console.log(data);
                    if(data.status === 'success'){
//                        $item.fadeOut(function(){
//                            $item.remove();
//                            if($('#unconfirmed-orders .order-g-item').length == 0){
//                                $('#unconfirmed-orders').fadeOut();
//                            }
//                        });
                        if(window.getDiff){
                            window.getDiff();
                        }
                    } else{
                        common.toast('接受订单失败');
                    }
                });
            }

            function showConfirmedOrderList(orders){
                resetConfirmedOrdersList();
                console.log(orders);
                $.each(orders,function (index,orderItem) {
                     showConfirmedItem(orderItem);
                });
            }

            function showConfirmedItem(orderItem,isPrepend){
                if(orderItem.state === OrderState.confirmed){
                    var $item = cloneWaiterHomeOrderItem();
                    setOrderItemCommonStatus($item,orderItem);
                    $item.on('click',function(){
                        var oId = $(this).attr('order-id');
                        location.href="#action=waiter_order&orderId="+oId+'&from=首页';
                    });
                    setConfirmedOrderItem($item);
                    if(isPrepend){
                        $('#confirmed-orders .title').after($item);
                    }else{
                        $('#confirmed-orders').append($item);
                    }

                }
            }

            function ifHideConfirmedList(){
                if(!$('#confirmed-orders .order-g-item').length){
                    $('#confirmed-orders').hide();
                    showNoOrders();
                }
            }


            /**
             * 显示未确认订单
             * @param orders
             */
            function showUnconfirmedOrderList(orders){
                resetUnconfirmedOrdersList();
                console.log(orders);
                $.each(orders,function (index,orderItem) {
                    showUnconfirmedOrderItem(orderItem);
                });
            }
            /**
             * 判断是否需要隐藏未确认的列表
             */
            function ifHideUnconfirmedList(){
                if(!$('#unconfirmed-orders .order-g-item').length){
                    $('#unconfirmed-orders').hide();

                    showNoOrders();
                }
            }


            function showUnconfirmedOrderItem(orderItem) {
                if(orderItem.state === OrderState.unconfirmed){
                    if($('#unconfirmed-orders').is(':hidden')){
                        console.log('显示 unconfirmed-orders');
                        $('#unconfirmed-orders').show();
                        hideNoOrders();
                    }

                    var $item = cloneWaiterHomeOrderItem();
                    setOrderItemCommonStatus($item,orderItem);
                    $item.on('click',function(){
                        var oId = $(this).attr('order-id');
                        location.href="#action=waiter_order&subOrderId="+oId+'&from=首页';
                    });
                    setUnconfirmedOrderItem($item);
                    $('#unconfirmed-orders').append($item);
                }
            }

            /**
             * 隐藏没有订单时的提示信息
             *
             */
            function hideNoOrders(){
                $('.home-orders-body .no-message').hide();
            }
            /**
             * 显示没有订单情况下的提示
             */
            function showNoOrders(){
                console.log('showNoOrders');
                if(!($('#unconfirmed-orders .order-g-item').length) && !($('#confirmed-orders .order-g-item').length)){
                    console.log('show no orders ----------------');
                    var height = $('#nav-waiter-content').height();
                    $('.home-orders-body .no-message').css({'line-height':height+'px'}).show();
                }else{
                    hideNoOrders();
                }
            }

            showStoreTables();
            getStoreOrders();
        }());
    </script>
</div>